package com.zixi.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    @RequestMapping({"/", "/index", "/index.html"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "Hello,Shiro!");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }


    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        //登录这个令牌
        try {
            subject.login(usernamePasswordToken);//执行登录方法，没有异常则成功了
            //登录成功将用户名给予session
            Subject currentSubject = SecurityUtils.getSubject();
            currentSubject.getSession().setAttribute("loginUsername", username);

            return "index";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg", "用户名错误！");
            return "login";
        } catch (IncorrectCredentialsException e) {//密码不存在
            model.addAttribute("msg", "密码错误！");
            return "login";
        }

        //以上操作存在与整个全局的关系 都能调用得到UserRealm
    }

    @RequestMapping("/Unauthorized")
    public String unauthorized(Model model) {
        return "unauthorized";
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();//当前用户退出
        return "index";
    }

    @RequestMapping("/testBlockStaticResources")
    public String testBlockStaticResourcesFolder() {
        return "TestBlockStaticResourcesFolder/test";
    }
}
